package efr.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import efr.dao.RimaDao;
import efr.dao.impl.RimaDaoImpl;
import efr.entity.Rima;
import efr.util.HibernateUtil;

/**
 * Servlet implementation class Op4RimaSubmitServlet
 */
public class Op4RimaSubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(Op4RimaSubmitServlet.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Op4RimaSubmitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		if("Modifica".equals(request.getParameter("action"))){
			String cuvant = request.getParameter("cuvant");
			String id = request.getParameter("id");
			Rima rima = new Rima();
			rima.setCuvant(cuvant);
			rima.setId(Integer.valueOf(id));
			RimaDao rimaDao = new RimaDaoImpl();
			try {
				rimaDao.updateRima(rima);
			} catch (Exception e) {
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
				HibernateUtil.getSessionFactory().getCurrentSession().close();
				logger.error("Error", e);
			}
		}
		if("Adauga".equals(request.getParameter("action"))){
			String cuvant = request.getParameter("cuvant");
			Rima rima = new Rima();
			rima.setCuvant(cuvant);
			RimaDao rimaDao = new RimaDaoImpl();
			try {
				Integer id = rimaDao.addRima(rima);
				logger.debug("S-a adaugat rima cu id ul "+id);
			} catch (Exception e) {
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
				HibernateUtil.getSessionFactory().getCurrentSession().close();
				logger.error("Error", e);
			}

		}
		RequestDispatcher view = request.getRequestDispatcher("/ListRime.do");
		view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
